package com.lagou.module01.servlet;

import com.lagou.module01.bean.Student;
import com.lagou.module01.service.imp.StudentServiceImp;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: xyk
 * @Date: Create in 22:52 2021/3/18
 * @Description:
 */
@WebServlet(name = "AddStudentServlet", urlPatterns = "/addStudentServlet")
public class AddStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        // service层获取学员信息
        StudentServiceImp studentServiceImp = new StudentServiceImp();

        String id = request.getParameter("id");
        String name = request.getParameter("userName");
        String sex = request.getParameter("sex");
        String birthday = request.getParameter("birthday");
        String email = request.getParameter("email");
        String remark = request.getParameter("remark");

        try {
            // 编辑学生信息
            if (studentServiceImp.queryStudentsService(id) != null){
                studentServiceImp.editStudentsService(new Student(id, name, sex, birthday, email, remark));
            }else {
                // 添加学生
                studentServiceImp.insertStudentsService(new Student(id, name, sex, birthday, email, remark));
            }
        }
        catch (Exception e){
            out.print(e);
        }
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/pageQueryServlet");
        requestDispatcher.forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
